import { setFormatteMenu } from '@/utils/formateMenu'
import router from '@/router'
import { RequestMenuList } from '@/api/user'

export const Menu = {
	state: {
		isCollapse:true,  // 菜单收缩
		menuList: [] //菜单数组
	},
	mutations: {
		SAVE_MENU(state, menuList) {
			state.menuList = menuList
		},
		CLEAR_MENU(state) {
			state.menuList = []
		},
		SET_COLLAPSE(state){
			state.isCollapse = !state.isCollapse
		}
	},
	actions: {
		saveMenu({ commit }, roleId) {
			// menuList 根据登录用户角色调用菜单接口返回
			return new Promise((resolve,reject)=>{
				RequestMenuList(roleId).then(data => {
					if (data.code == 200) {
						//菜单数据过滤 
						let routesMenu = setFormatteMenu(data.sysmenu)
						commit('CLEAR_MENU') // 先清除原来菜单数据
						commit('SAVE_MENU', routesMenu)
						router.addRoutes(routesMenu) // 动态添加路由
						resolve(1)
					}else{
						reject(-1)
					}
				})
			})
		},
		clearMenu({ commit }) {
			commit('CLEAR_MENU')
		},
		setCollapse({commit}){
			commit('SET_COLLAPSE')
		}
	}
}
